package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 登录
     *
     * @param code
     * @return {@link UserLoginVO}
     */
    @Override
    public UserLoginVO login(String code) {
        String openid = getOpenid(code);

        if (Objects.isNull(openid)){
            //todo openid 不存在,抛出异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.selectByOpenid(openid);
        if(Objects.isNull(user)){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            //需要主键返回
            userMapper.insert(user);
        }
        //3.实现结果的拼装和返回
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setOpenid(openid);
        //创建jwt
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        userLoginVO.setToken(token);


        return userLoginVO;
    }

    /**
     * 获取Openid
     *
     * @param code
     * @return {@link String}
     */
    private String getOpenid(String code) {
        HashMap<String,String> params = new HashMap<>();
        params.put("appid",weChatProperties.getAppid());
        params.put("secret",weChatProperties.getSecret());
        params.put("js_code", code);
        params.put("grant_type","authorization_code");
        String responseJson = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", params);
        //解析 jsonObject -- 拿到openid
        JSONObject jsonObject = JSON.parseObject(responseJson);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
